package com.gameserver;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.UUID;

import org.json.*;

public class Game {

	ArrayList<Turn> turns;
	int playerTurn;
	int turnNumber;
	int gameID;
	Turn currentTurn;
	boolean isAccepting;
	InetAddress player1;
	InetAddress player2;
	
	GameState state;
	
	public Game(int id)
	{
		gameID = id;
		playerTurn = 1;
		turnNumber = 1;
		turns = new ArrayList<Turn>();
		currentTurn = new Turn(turnNumber);
		player1 = null;
		player2 = null;
		isAccepting = true;
		state = GameState.NOPLAYERS;
	}
	
	public int getPlayerTurn()
	{
		return playerTurn;
	}
	
	public int getCurrentTurn()
	{
		return turnNumber;
	}
	
	
	public void addPlayerTurn(JSONObject turnData)
	{
		if(state == GameState.WAITINGPLAYER1)
		{
			state = GameState.READYPLAYER2;
			currentTurn.player1Move = turnData;
			playerTurn = 2;
		}else if(state == GameState.WAITINGPLAYER2){
			state = GameState.READYPLAYER1;
			currentTurn.player2Move = turnData;
			turns.add(currentTurn);
			turnNumber++;
			currentTurn = new Turn(turnNumber);
			playerTurn = 1;
		}
	}
	
	public void addPlayer(InetAddress addr)
	{
		if(state == GameState.NOPLAYERS)
		{
			player1 = addr;
			state = GameState.NEED1PLAYER;
		}else if(state == GameState.NEED1PLAYER)
		{
			player2 = addr;
			state = GameState.WAITINGPLAYER1;
		}	
	}
	
	public boolean isDataReady(InetAddress ip)
	{
		return false;
	}
	
	public JSONObject getMoveData(InetAddress ip) 
	{
		if(state == GameState.READYPLAYER1)
		{
			return turns.get(turns.size() - 1).player2Move;
		}else if (state == GameState.READYPLAYER2)
		{
			return currentTurn.player1Move;
		}else{
			return null;
		}
	}
	
	public enum GameState
	{
		NOPLAYERS, NEED1PLAYER, WAITINGPLAYER1, READYPLAYER2,
		WAITINGPLAYER2, READYPLAYER1, WONREADY, WONFINISHED
	}
}
